package com.httpdemo.http_teaching_server.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/param")
public class ParameterController {

    // 1️⃣ Query String   GET
    @GetMapping("/query")
    public Map<String, Object> query(@RequestParam String q, @RequestParam(defaultValue = "1") int page) {
        return Map.of("type", "query", "q", q, "page", page);
    }

    // 2️⃣ Path Variable   GET
    @GetMapping("/path/{id}")
    public Map<String, Object> path(@PathVariable Long id) {
        return Map.of("type", "path", "id", id);
    }

    // 3️⃣ x-www-form-urlencoded   POST
    @PostMapping(value = "/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Map<String, Object> form(@RequestParam Map<String, String> map) {
        return Map.of("type", "form", "data", map);
    }

    // 4️⃣ multipart/form-data   POST
    @PostMapping(value = "/multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String, Object> multipart(@RequestPart("file") MultipartFile file,
                                         @RequestPart("desc") String desc) {
        return Map.of("type", "multipart",
                "fileName", file.getOriginalFilename(),
                "size", file.getSize(),
                "desc", desc);
    }

    // 5️⃣ application/json   POST
    @PostMapping(value = "/json", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> json(@RequestBody Map<String, Object> body) {
        return Map.of("type", "json", "body", body);
    }

    // 6️⃣ application/xml   POST
    @PostMapping(value = "/xml", consumes = MediaType.APPLICATION_XML_VALUE)
    public Map<String, Object> xml(@RequestBody String xml) {
        return Map.of("type", "xml", "raw", xml);
    }

    // 7️⃣ text/plain   POST
    @PostMapping(value = "/plain", consumes = MediaType.TEXT_PLAIN_VALUE)
    public Map<String, Object> plain(@RequestBody String text) {
        return Map.of("type", "plain", "text", text);
    }

    // 8️⃣ binary / octet-stream   POST
    @PostMapping(value = "/binary", consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Map<String, Object> binary(@RequestBody byte[] bytes) {
        return Map.of("type", "binary", "length", bytes.length);
    }

    // 9️⃣ GraphQL  (POST + JSON body)
    @PostMapping(value = "/graphql", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> graphql(@RequestBody Map<String, Object> payload) {
        return Map.of("type", "graphql", "query", payload.get("query"));
    }
}